#include <ani.h>
#include <array>
#include <iostream>
#include <unistd.h>

static int execute([[maybe_unused]] ani_env *env, [[maybe_unused]] ani_object obj, [[maybe_unused]] ani_object want)
{
    std::cout << "Print in execute in thread" << gettid() <<std::endl;

    //当前不支持 Object_GetField_Int
    // ani_class cls;
    // const char *className = "Lpromise_test/Want;";
   
    // if(ANI_OK != env->FindClass(className, &cls)) {
    //     std::cerr << "Not found '" << className << "'" << std::endl;
    //     return -1;
    // }
   
    // ani_field  valueField;
    // if(ANI_OK != env->Class_GetField(cls, "value", &valueField) ) {
    //      std::cerr << "Get Field Fail" << "'" << std::endl;
    //      return -1;
    // }

    // ani_int value;
    // if(ANI_OK != env->Object_GetField_Int(want, valueField, &value)){
    //     std::cerr << "Object_GetField_Int Fail" << std::endl;
    //     return -1;
    // }

    //std::cout << "Print in execute want value is " << value <<std::endl;
    return 5;
}

static int mygettid([[maybe_unused]] ani_env *env, [[maybe_unused]] ani_object obj){
    return gettid();
}

ANI_EXPORT ani_status ANI_Constructor(ani_vm *vm, uint32_t *result)
{
    ani_env *env;
    if (ANI_OK != vm->GetEnv(ANI_VERSION_1, &env)) {
        std::cerr << "Unsupported ANI_VERSION_1" << std::endl;
        return ANI_ERROR;
    }

    static const char *className = "ani_promise.Ability";
    ani_class cls;
    if (ANI_OK != env->FindClass(className, &cls)) {
        std::cerr << "Not found '" << className << "'" << std::endl;
        return ANI_ERROR;
    }

    std::array methods = {
        ani_native_function {"execute", "C{ani_promise.Want}:i", reinterpret_cast<void *>(execute)},
        ani_native_function {"gettid", ":i", reinterpret_cast<void *>(mygettid)},
    };

    if (ANI_OK != env->Class_BindNativeMethods(cls, methods.data(), methods.size())) {
        std::cerr << "Cannot bind native methods to '" << className << "'" << std::endl;
        return ANI_ERROR;
    };

    *result = ANI_VERSION_1;
    return ANI_OK;
}